home *** CD-ROM | disk | FTP | other *** search
/ Apple Developer Connection Student Program / ADC Tools Sampler CD Disk 3 1999.iso / Documentation / Books / Learn Java on the Macintosh / Learn Java Projects / 08.06 - next prime 3 / NextPrime3.java < prev    next >
Text File  |  1996-04-22  |  842b  |  40 lines

  1. /* -------------------------------------------------------------
  2. This applet finds the primes between 1 and 100.
  3.  
  4. Java's classes: Applet    (applet)
  5.                 System    (lang)
  6.  
  7. Custom classes: IsOdd
  8.  
  9. ------------------------------------------------------------- */
  10.  
  11. public class NextPrime3 extends java.applet.Applet {
  12.     public void init() {
  13.     
  14.         int        primeIndex, candidate, i, last;
  15.         boolean isPrime;
  16.     
  17.         System.out.println( "Prime #1 is 2." );
  18.     
  19.         candidate = 3;
  20.         primeIndex = 2;
  21.     
  22.         while ( primeIndex <= 100 ) {
  23.         
  24.             isPrime = true;
  25.             last = (int)Math.sqrt( candidate );
  26.         
  27.             for ( i = 3; (i <= last) && isPrime; i += 2 ) {
  28.                 if ( (candidate % i) == 0 )
  29.                     isPrime = false;
  30.             }
  31.         
  32.             if ( isPrime ) {
  33.                 System.out.println( "Prime " + primeIndex + " is " + candidate );
  34.                 primeIndex++;
  35.             }
  36.         
  37.             candidate += 2;
  38.         }
  39.     }
  40. }